package czk.concrent.threadpool.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/9/30 14:12
 */
public class CompletableFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // test2();
        test3();
    }

    public static void test1() throws ExecutionException, InterruptedException {
        CompletableFuture future = CompletableFuture.supplyAsync(new Supplier<Integer>() {

            @Override
            public Integer get() {
                return 122;
            }
        });
        future.whenComplete((key, value) -> {
            System.out.println(key);
            System.out.println(value);
        });
        System.out.println(future.get());
    }

    public static void test2() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 100;
        });
        CompletableFuture<Void> czk = integerCompletableFuture.thenRun(() -> {
            System.out.println("czk");
        });
        //
        TimeUnit.SECONDS.sleep(3);
        // 先输出
        System.out.println(integerCompletableFuture.get());
    }

    public static void test3() {
        CompletableFuture.supplyAsync(() -> 1)
                .thenApply(i -> i + 1)
                .thenApply(i -> i * i)
                .whenComplete((v, r) -> System.out.println(r));
    }
}
